import { Injectable } from '@nestjs/common';
import Stripe from 'stripe';
import { ConfigService } from '@nestjs/config';

@Injectable()
export class StripeService {
  private stripe: Stripe;
  private webhookSecret: string;

  constructor(private configService: ConfigService) {
    const secretKey = this.configService.get<string>('STRIPE_SECRET_KEY');

    if (!secretKey) {
      throw new Error(
        'STRIPE_SECRET_KEY is not defined in environment variables',
      );
    }

    this.stripe = new Stripe(secretKey, {
      apiVersion: '2025-11-17.clover',
    });

    this.webhookSecret =
      this.configService.get<string>('STRIPE_WEBHOOK_SECRET') || '';
  }

  /**
   * 创建支付意图
   * @param amount 金额（分）
   * @param currency 货币代码
   * @param description 描述
   * @returns PaymentIntent
   */
  async createPaymentIntent(
    amount: number,
    currency: string,
    description: string,
  ) {
    return this.stripe.paymentIntents.create({
      amount,
      currency,
      description,
    });
  }

  /**
   * 验证Webhook签名
   * @param payload 请求体
   * @param signature 签名
   * @returns Event
   */
  constructEvent(payload: Buffer, signature: string) {
    if (!this.webhookSecret) {
      throw new Error(
        'STRIPE_WEBHOOK_SECRET is not defined in environment variables',
      );
    }

    return this.stripe.webhooks.constructEvent(
      payload,
      signature,
      this.webhookSecret,
    );
  }
}
